package com.fz.song.feibao.web.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fz.song.feibao.framework.common.enums.IsDelEnum;
import com.fz.song.feibao.web.entity.Admin;
import com.fz.song.feibao.web.mapper.AdminMapper;
import com.fz.song.feibao.web.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 宋发准
 * @since 2021-10-29
 */
@Service
@Slf4j
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Value("${feibao.admin.username}")
    private String username;

    @Value("${feibao.admin.password}")
    private String password;

    @Value("${feibao.admin.user-key}")
    private String userKey;


    /**
     * 初始化管理员
     */
    @Override
    public void initAdmin() {
        LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Admin::getAdmin, 1);
        Admin admin = getOne(wrapper);
        if (admin == null) {
            log.info("系统启动完成,开始初始化管理员,用户名:{},:密码:{}", username, password);
            String pwd = SaSecureUtil.md5BySalt(password, userKey);
            admin = new Admin();
            admin.setUsername(username);
            admin.setPassword(pwd);
            admin.setState(1);
            admin.setAdmin(1);
            admin.setDel(0);
            admin.setRegisterTime(LocalDateTime.now());
            admin.setCreateTime(LocalDateTime.now());
            admin.setUpdateTime(LocalDateTime.now());
            save(admin);
        }

    }

    /**
     * 根据用户名查询用户信息
     *
     * @param username 用户名
     * @return User
     */
    @Override
    public Admin getByUsername(String username) {
        LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Admin::getUsername, username);
        wrapper.eq(Admin::getDel, IsDelEnum.NOT_DEL.getDel());
        return getOne(wrapper);
    }
}
